<!-- <template>
  <div>
    <div style="height: 0px">
      <strong
        style="
          display: block;
          margin-top: 10px;
          text-align: center;
          font-size: 40px;
        "
        >精准靶向发布</strong
      >
    </div>
    <div className="hello">
      <div className="box">
        <div className="map">
          <div id="map" ref="map"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useStore } from "vuex";
import { onMounted, onUnmounted, toRaw, watch } from "vue";
import geoJson from "@/assets/yuegangao.json";
import regionStylesData from "@/assets/regionStyles.json";
import { getUserInfoData } from "@/api/user/UserInfo";
import L from "leaflet";
import LogininVue from "../../../page/login/Loginin.vue";

export default {
  name: "BXFB",
  mounted() {
    this.$emit("changeTimeIndex", 16);
    this.$emit("changeIsSelect2", false);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", false);
  },
  setup() {
    let mymap;
    let markerLayer = L.layerGroup();
    const store = useStore();
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10,
    };

    let params = {
      lon: 110,
      lat: 20,
      temp: 20,
      hum: 20,
      wind: 5,
      vis: 10,
      pre: 1000,
      dir: 100,
      deg: 11,
    };
    const getBxfbData = () => {
      return toRaw(store.state.bxfbData);
    };

    onMounted(() => {
      initMap();
      updateMap();
    });
    onUnmounted(() => {
      if (mymap) {
        mymap.remove();
        mymap = null;
      }
    });

    watch(
      () => store.state.bxfbData,
      (newValue, oldValue) => {
        console.log("bxfbData changed:", newValue);
        // 在这里可以执行一些逻辑来处理bxfbData的变化
        let myData = getBxfbData();
        console.log(myData);
        params.lon = newValue.longitude;
        params.lat = newValue.latitude;
        params.temp = newValue.temperature;
        params.hum = newValue.humidity;
        params.wind = newValue.windSpeed;
        params.vis = newValue.visibility;
        params.pre = newValue.pressure;
        params.dir = newValue.windDirection;
        params.deg = newValue.degree;
        console.log(params, "新数据");
        updateMap();
      }
      // { deep: true }
    );

    async function initMap() {
      const guangdongCenter = [23.125178, 113.280637];
      mymap = L.map("map", { attributionControl: false }).setView(
        guangdongCenter,
        7
      );

      // 切换底图
      //矢量地图
      const tileLayer1 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地图
      const tileLayer2 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //矢量地名
      const tileLayer3 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地名
      const tileLayer4 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      const baseMaps = {
        区划图: L.layerGroup([tileLayer1, tileLayer3]),
        地形图: L.layerGroup([tileLayer2, tileLayer4]),
      };
      tileLayer1.addTo(mymap);
      tileLayer3.addTo(mymap);
      L.control.layers(baseMaps).addTo(mymap);

      // 设置地图缩放范围
      mymap.setMinZoom(4);
      mymap.setMaxZoom(15);

      // 中国边界GeoJSON图层
      L.geoJSON(geoJson, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
          fillOpacity: 0.1,
        },
      }).addTo(mymap);

      function highlightFeature(e) {
        const layer = e.target;
        layer.setStyle({
          weight: 3,
          color: "#767676",
          fillColor: "#767676",
          dashArray: "",
          fillOpacity: 0.7,
        });
        layer.bringToFront();
      }

      function resetHighlight(e) {
        geojson.resetStyle(e.target);
      }

      // function zoomToFeature(e) {
      // 	map.fitBounds(e.target.getBounds());
      // }

      function onEachFeature(feature, layer) {
        layer.on({
          mouseover: highlightFeature,
          mouseout: resetHighlight,
          // click: zoomToFeature
        });
      }

      // 广东边界GeoJSON图层
      const geojson = L.geoJSON(regionStylesData, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
        },
        onEachFeature,
      }).addTo(mymap);

      return mymap;
    }

    async function updateMap() {
      // console.log(myData);

      // 清除之前添加的所有标记图层
      markerLayer.clearLayers();

      //天气点
      const weatherMarker = L.circleMarker([params.lat, params.lon], {
        radius: 5,
        color: "red",
        fillOpacity: 1,
        fillColor: "red",
      });
      weatherMarker.on("mouseover", function (e) {
        const popupContent = `
             <div>
               <p>经度: ${params.lon}   纬度: ${params.lat}   温度: ${params.temp}</p >
               <p>湿度: ${params.hum}   风速: ${params.wind}   能见度: ${params.vis}</p >
               <p>气压: ${params.pre}   方向: ${params.dir}   角度: ${params.deg}</p >
             </div>
           `;
        weatherMarker.bindPopup(popupContent).openPopup();
      });
      weatherMarker.on("mouseout", function (e) {
        weatherMarker.closePopup();
      });
      markerLayer.addLayer(weatherMarker);

      //用户点
      const data = await fetchData(params);
      console.log("用户数据", data);

      if (data === null) {
        showTopMessage("当前没有相关数据", 2000);
      } else {
        const userData = data.user_info;
        const filteredData = userData.filter((user) => user[6] >= 1); // 筛选评分大于等于1的用户
        if (filteredData.length === 0) {
          showTopMessage("没有要发布的预警", 2000);
        } else {
          const topUsers = filteredData.slice(0, 10); // 获取评分最高的前10个用户
          topUsers.forEach((user) => {
            const lat = user[5];
            const lon = user[4];
            const score = user[6];
            const diameter = 5000; // 根据评分计算直径
            const userInfo = {
              userId: user[0],
              gender: user[2],
              age: user[1],
              longitude: user[4],
              latitude: user[5],
              score: user[6],
            };
            const UserMarker = L.circle([lat, lon], {
              radius: diameter,
              color: "blue",
              fillOpacity: 0.5,
              fillColor: "blue",
            }).addTo(markerLayer);

            // const iconHtml = `<div style="width: ${diameter}px; height: ${diameter}px; background-color: blue; border-radius: 50%; opacity: 0.5;"></div>`;
            // const icon = L.divIcon({
            //   className: "custom-icon",
            //   html: iconHtml,
            // });
            // const marker = L.marker([lat, lon], { icon: icon }).addTo(
            //   markerLayer
            // );

            UserMarker.on("mouseover", () => {
              UserMarker.bindPopup(createPopupContent(userInfo, params)).openPopup();
            });
            UserMarker.on("mouseout", () => {
              UserMarker.closePopup();
            });
          });
          // 根据参数生成预警信息
          function generateWarning(parameters) {
            let warnings = [];
            if (parameters.temp >= 35) {
              warnings.push("高温预警");
            } else if (parameters.temp <= -3) {
              warnings.push("霜冻预警");
            }
            if (parameters.pre <= 1000) {
              warnings.push("台风预警");
            }
            // 可以添加更多的条件判断来生成不同的预警信息
            if (parameters.hum <= 80 && parameters.vis <= 3) {
              warnings.push("霾预警");
            } else if (parameters.hum >= 90 && parameters.vis <= 0.5) {
              warnings.push("大雾预警");
            }
            if (parameters.wind >= 17.2) {
              warnings.push("大风预警");
            }
            // 如果没有任何预警，可以返回一个默认消息或空字符串
            return warnings.length > 0 ? warnings.join("，") : "无预警";
          }
          function createPopupContent(userInfo, parameters) {
            const { userId, gender, age, longitude, latitude, score } =
              userInfo;
            const warning = generateWarning(parameters);
            const genderText = gender === 0 ? "男" : "女";
            return `
             <div>
               <p>用户ID: ${userId}</p >
               <p>性别: ${genderText}</p >
               <p>年龄: ${age}</p >
               <p>经度: ${longitude}</p >
               <p>纬度: ${latitude}</p >
               <p>评分: ${score}</p >
               <p>预警发布: ${warning}</p >
             </div>
           `;
          }
        }

        markerLayer.addTo(mymap);
      }

      async function fetchData(params) {
        try {
          const Data = await getUserInfoData(params);
          return Data;
        } catch (error) {
          console.error("Error fetching data:", error);
          return null;
        }
      }

      function showTopMessage(message, duration) {
        // 创建一个提示元素
        const messageElement = document.createElement("div");
        messageElement.className = "top-message";
        messageElement.textContent = message;

        // 将提示元素添加到页面的顶部
        document.body.appendChild(messageElement);

        // 设置定时器，在一定时间后自动隐藏提示
        setTimeout(() => {
          messageElement.style.opacity = "0"; // 渐变消失
          setTimeout(() => {
            document.body.removeChild(messageElement); // 删除提示元素
          }, 1000); // 在渐变结束后删除元素
        }, duration);

        // 自定义样式
        messageElement.style.position = "fixed";
        messageElement.style.top = "100px";
        messageElement.style.left = "42%";
        messageElement.style.width = "300px";
        messageElement.style.borderRadius = "4px";
        messageElement.style.backgroundColor = "#88bffa";
        messageElement.style.color = "#fff";
        messageElement.style.padding = "10px 0";
        messageElement.style.textAlign = "center";
        messageElement.style.transition = "opacity 1s ease-in-out";
      }

      return {
        getBxfbData,
      };
    }
  },
};
</script>

<style scoped lang="scss">
.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (min-width: 700px) {
  .map {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #map {
      width: 100%;
      height: 65vh;
    }
  }
}

.custom-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.custom-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.custom-button:hover {
  background-color: #0056b3;
}
</style> -->

<template>
  <div>
    <div style="height: 0px">
      <strong
        style="
          display: block;
          margin-top: 10px;
          text-align: center;
          font-size: 40px;
        "
        >精准靶向发布</strong
      >
    </div>
    <div className="hello">
      <div className="box">
        <div className="map">
          <div id="map" ref="map"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import L from "leaflet";
import { useStore } from "vuex";
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import geoJson from "@/assets/yuegangao.json";
import regionStylesData from "@/assets/regionStyles.json";
import pako from "pako";
import { getUsersData } from "@/api/user/usersdata";
import {CanvasLabel} from "@panzhiyue/leaflet-canvaslabel";

export default {
  name: "BXFB",
  props: {
    totalData: {
      default: null,
    },
  },
  mounted() {
    this.$emit("changeTimeIndex", 19);
    this.$emit("changeIsSelect2", false);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", true);
  },

  setup(props) {
    const totalData = reactive(props.totalData);
    // console.log(totalData, "123456");
    watch(
      () => props.totalData,
      (newVal) => {
        console.log("totalData 发生了更改", newVal);
        totalData.value = newVal;
        params.year = newVal.getFullYear();
        params.month = newVal.getMonth() + 1;
        params.day = newVal.getDate();
        params.hour = newVal.getHours();
        params.minute = newVal.getMinutes();
        console.log("new params:", params);
        updateMap();
      },
      { deep: true }
    );

    let usersData = ref([]);
    let mymap;
    let markerLayer = L.layerGroup();
    const store = useStore();
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10,
    };

    const COLORS = ["#3366FF", "#FFFF00", "#FC9B00", "#D72E29"];

    let params = {
      year: 2023,
      month: 9,
      day: 30,
      hour: 0,
      minute: 0,
    };

    onMounted(() => {
      initMap();
      updateMap();
    });
    onUnmounted(() => {
      if (mymap) {
        mymap.remove();
        mymap = null;
      }
    });

    async function initMap() {
      const guangdongCenter = [23.125178, 113.280637];

      var canvasLabel = new L.CanvasLabel({
            defaultLabelStyle: {
              collisionFlg: false,
              scale: 1,
              strokeStyle: "rgba(0,0,0,1)",
              fillStyle: "rgba(0,0,0,1)",
              lineWidth:3
            },
            clearAlpha: 0,
      });
      
      mymap = L.map("map", { attributionControl: false, renderer: canvasLabel }).setView(
        guangdongCenter,
        7
      );

      // 切换底图
      //矢量地图
      const tileLayer1 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地图
      const tileLayer2 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //矢量地名
      const tileLayer3 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地名
      const tileLayer4 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      const baseMaps = {
        区划图: L.layerGroup([tileLayer1, tileLayer3]),
        地形图: L.layerGroup([tileLayer2, tileLayer4]),
      };
      tileLayer1.addTo(mymap);
      tileLayer3.addTo(mymap);
      L.control.layers(baseMaps).addTo(mymap);

      // 设置地图缩放范围
      mymap.setMinZoom(4);
      mymap.setMaxZoom(10);

      // 中国边界GeoJSON图层
      L.geoJSON(geoJson, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
          fillOpacity: 0.1,
        },
      }).addTo(mymap);

      function highlightFeature(e) {
        const layer = e.target;
        layer.setStyle({
          weight: 3,
          color: "#767676",
          fillColor: "#767676",
          dashArray: "",
          fillOpacity: 0.7,
        });
        layer.bringToFront();
      }

      function resetHighlight(e) {
        geojson.resetStyle(e.target);
      }

      // function zoomToFeature(e) {
      // 	map.fitBounds(e.target.getBounds());
      // }

      function onEachFeature(feature, layer) {
        layer.on({
          mouseover: highlightFeature,
          mouseout: resetHighlight,
          // click: zoomToFeature
        });
      }

      // 广东边界GeoJSON图层
      const geojson = L.geoJSON(regionStylesData, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
        },
        onEachFeature,
      }).addTo(mymap);

      //色标控件
      const legend = L.control({ position: "bottomright" });
      legend.onAdd = function (map) {
        const div = L.DomUtil.create("div", "legend");
        const grades = ['暴雨蓝色预警', '暴雨黄色预警', '暴雨橙色预警', '暴雨红色预警'];
        const colors = [];
        const labels = [];
        for (let i = 0; i < grades.length; i++) {
          let from = grades[i];
          colors.push(
            `<i style="background: ${COLORS[i]};width: 12px; margin-left:36px; height: 12px; float: left; opacity: 1; margin-right: 30px"></i>`
          );
          labels.push(
            `<i style="width: 80px; height: 18px; text-align: center; float: left; font-style: normal;">${from}</i>`
          );
        }
        div.innerHTML = `<div style="background-color: white; width: 330px; height: 42px; padding:5px">
                   ${colors.join("") + "<br>" + labels.join("")}</div>`;
        return div;
      };
      legend.addTo(mymap);

      return mymap;
    }

    async function updateMap() {
      markerLayer.clearLayers();
      const data = await fetchData(params);
      if (data === null) {
        showTopMessage("当前没有相关数据", 2000);
      } else {
        let UsersData = Object.values(data)[0];
        function getColor(d) {
          return d >= 4
            ? COLORS[3]
            : d >= 3
            ? COLORS[2]
            : d >= 2
            ? COLORS[1]
            : COLORS[0];
        }
        if (UsersData.length === 0) {
          showTopMessage("没有要发布的预警", 2000);
        } else {
          console.log(UsersData);
          UsersData.forEach((user) => {
            const lat = user[2];
            const lon = user[1];
            const score = user[3] | 0;
            const diameter = 1; // 根据评分计算直径
            const userInfo = {
              userId: user[0] | 0,
              longitude: lon,
              latitude: lat,
            };
            const UserMarker = L.circleMarker([lat, lon], {
              radius: diameter,
              color: getColor(score),
              fillOpacity: 1,
              fillColor: getColor(score),
              labelStyle: {
                rotation: 0,
                zIndex: 1,
                //minZoom : 6,
                strokeStyle: "red",
              }
            }).addTo(markerLayer);

            UserMarker.on("mouseover", () => {
              UserMarker.bindPopup(createPopupContent(userInfo, params)).openPopup();
            });
            UserMarker.on("mouseout", () => {
              UserMarker.closePopup();
            });
          });
          
          function createPopupContent(userInfo, parameters) {
            const { userId, longitude, latitude } =
              userInfo;
            return `
             <div>
               <p>用户ID: ${userId}</p >
               <p>经度: ${longitude}</p >
               <p>纬度: ${latitude}</p >
             </div>
           `;
          }
        }

        markerLayer.addTo(mymap);
      }
    }

    async function fetchData(params) {
      try {
        let Data = await getUsersData(params); // 使用接口文件中的函数获取数据
        return Data;
      } catch (error) {
        console.error("Error fetching Users data:", error);
        return null;
      }
    }
    function showTopMessage(message, duration) {
      // 创建一个提示元素
      const messageElement = document.createElement("div");
      messageElement.className = "top-message";
      messageElement.textContent = message;

      // 将提示元素添加到页面的顶部
      document.body.appendChild(messageElement);

      // 设置定时器，在一定时间后自动隐藏提示
      setTimeout(() => {
        messageElement.style.opacity = "0"; // 渐变消失
        setTimeout(() => {
          document.body.removeChild(messageElement); // 删除提示元素
        }, 1000); // 在渐变结束后删除元素
      }, duration);

      // 自定义样式
      messageElement.style.position = "fixed";
      messageElement.style.top = "100px";
      messageElement.style.left = "42%";
      messageElement.style.width = "300px";
      messageElement.style.borderRadius = "4px";
      messageElement.style.backgroundColor = "#88bffa";
      messageElement.style.color = "#fff";
      messageElement.style.padding = "10px 0";
      messageElement.style.textAlign = "center";
      messageElement.style.transition = "opacity 1s ease-in-out";
    }

    return {
      totalData,
    };
  },
};
</script>

<style scoped lang="scss">
.time-picker-fixed {
  position: fixed;
  top: 90%; /* 垂直居中 */
  left: 50%; /* 水平居中 */
  transform: translate(-50%, -50%); /* 居中偏移 */
  width: 1200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background-color: transparent;
}

.time-picker {
  justify-content: center;
  width: 400px;
  display: flex;
  flex-direction: row; /* 水平布局 */
  align-items: center;
  border: 3px solid #007bff;
  padding: 20px;
  border-radius: 8px;
  background-color: #f0f0f0;
}

.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (min-width: 700px) {
  .map {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #map {
      width: 100%;
      height: 65vh;
    }
  }
}

.custom-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.custom-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.custom-button:hover {
  background-color: #0056b3;
}
</style>

